package rsa_demo;
import java.security.*;
import java.util.Base64;

public class RSAKeyGenerator {
    public static void main(String[] args) throws NoSuchAlgorithmException {
        // 初始化密钥对生成器，指定算法为 RSA，密钥长度为 2048 位
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(2048);

        // 生成密钥对
        KeyPair keyPair = keyGen.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        // 将密钥转换为 Base64 编码，便于存储或传输
        String publicKeyBase64 = Base64.getEncoder().encodeToString(publicKey.getEncoded());
        String privateKeyBase64 = Base64.getEncoder().encodeToString(privateKey.getEncoded());

        System.out.println("公钥: " + publicKeyBase64);
        System.out.println("私钥: " + privateKeyBase64);
    }
}
